package main

import (
	"fmt"
	"go-xorm-01/utils"
	"time"
	"xorm.io/xorm"
	"xorm.io/xorm/log"
	"xorm.io/xorm/names"
)

var engine *xorm.Engine

// 软删除Deleted https://xorm.io/zh/docs/chapter-07/1.deleted/
// Deleted可以让您 不真正的删除数据，而是标记一个删除时间。
// 使用此特性需要在xorm标记中使用deleted标记，如下所示进行标记，对应的字段可以为time.Time, type MyTime time.Time，int 或者 int64类型。
func main() {
	SnakeMapper()
	//insetManyUser(engine)
	//engine.DumpAllToFile("demo07-delete/demo02-deleted/sql.sql")
	deleteUser(engine)

}

func deleteUser(engine *xorm.Engine) {
	//在Delete()时，deleted标记的字段将会被自动更新为当前时间而不是去删除该条记录，如
	var user UserDeleteD
	de, _ := engine.ID(1).Delete(user)
	fmt.Println(de)

	//那么如果记录已经被标记为删除后，要真正的获得该条记录或者真正的删除该条记录，需要启用Unscoped，如下所示：

	var user1 UserDeleteD
	engine.ID(1).Unscoped().Get(&user1)
	// 此时将可以获得记录
	engine.ID(1).Unscoped().Delete(&user1)
	// 此时将可以真正的删除记录
}

func SnakeMapper() {
	engine = utils.GenerateEngine()
	engine.SetMapper(names.SnakeMapper{}) // SnakeMapper 【默认】
	err := engine.Sync2(new(UserDeleteD))
	if err != nil {
		fmt.Printf("err:%v", err)
	}
	engine.ShowSQL(true)
	engine.SetLogLevel(log.LOG_DEBUG)

}

func insetManyUser(engine *xorm.Engine) {
	groupOne := make([]*UserDeleteD, 0)
	for i := 0; i < 5; i++ {
		groupOne = append(groupOne, &UserDeleteD{
			Username: fmt.Sprintf("zhangsan-%d", i),
			Password: fmt.Sprintf("123456-%d", i),
			GroupId:  1,
			Rank:     i,
		})
	}
	engine.Insert(groupOne)

	groupTwo := make([]*UserDeleteD, 0)
	for i := 0; i < 3; i++ {
		groupTwo = append(groupTwo, &UserDeleteD{
			Username: fmt.Sprintf("lisi-%d", i),
			Password: fmt.Sprintf("00000-%d", i),
			GroupId:  2,
			Rank:     i,
		})
	}
	engine.Insert(groupTwo)

}

type JsonTime time.Time

func (j JsonTime) MarshalJSON() ([]byte, error) {
	return []byte(`"` + time.Time(j).Format("2006-01-02 15:04:05") + `"`), nil
}

type UserDeleteD struct {
	Id        int64     `xorm:"pk autoincr"`                                              //指定列名 ，默认id
	Username  string    `xorm:"varchar(25) notnull unique(u_p) 'username' comment('姓名')"` //复合唯一索引
	Password  string    `xorm:"varchar(25) notnull unique(u_p) 'password' comment('密码')"` //复合唯一索引
	TimeOne   time.Time `xorm:"created"`
	TimeTwo   JsonTime  `xorm:"created"`
	TimeThree int64     `xorm:"created"`
	GroupId   int64
	Rank      int
	Version   int       `xorm:"version"`
	UpdatedAt time.Time `xorm:"updated"`
	DeletedAt time.Time `xorm:"deleted"`
}
